package sess

import (
	"fmt"
	"net"

	"gitee.com/night-tc/gobige/global"
	"github.com/xtaci/kcp-go"
	"golang.org/x/net/netutil"
)

/*
实现连接逻辑的包
*/

func GetListener(protocal string, info *global.ListenCfg) (result net.Listener, port int) {
	var err error
	for port = info.PortMin; port <= info.PortMax; port++ {
		switch protocal {
		case "tcp":
			result, err = net.Listen("tcp",
				fmt.Sprintf("%s:%d", info.Listen, port))
		case "kcp":
			result, err = kcp.Listen(fmt.Sprintf("%s:%d", info.Listen, port))
		default:
			panic("WRONG PROTOCAL")
		}
		if err == nil {
			break
		}
	}
	if err != nil {
		panic(err)
	}
	if info.MaxConn > 0 {
		result = netutil.LimitListener(result, info.MaxConn)
	}
	return
}
